﻿using System;
using System.Text;

namespace Rosetta.Default.AddIns.Text
{
    public abstract class EncodingConverter : Converter
    {
        #region Fields

        private readonly Encoding encoder;

        #endregion

        #region Constructors

        protected EncodingConverter([NotNull] string name, [NotNull] Encoding encoder)
            : base(name)
        {
            if (encoder == null)
            {
                throw new ArgumentNullException("encoder");
            }
            this.encoder = encoder;

            Category = "Text";

            Add<string, byte[]>("ToBytes", ToBytes, "s");
            Add<byte[], string>("ToString", ToString, "bytes");
        }

        #endregion

        #region Private Methods

        private byte[] ToBytes([NotNull] string s)
        {
            if (s == null)
            {
                throw new ArgumentNullException("s");
            }

            return encoder.GetBytes(s);
        }

        private string ToString([NotNull] byte[] bytes)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException("bytes");
            }

            return encoder.GetString(bytes);
        }

        #endregion
    }
}